package top.hkyzf.study.leetcode.array;

import org.junit.Test;

/**
 * @author 朱峰
 * @date 2022-2-10 9:49
 */
public class 最大子数组和_53 {
    public int maxSubArray1(int[] nums) {
        if (nums.length == 1) {
            return nums[0];
        }
        int[] re = new int[nums.length];
        re[0] = nums[0];
        int i = 1;
        int result = re[0];
        while (i < nums.length) {
            re[i] = Math.max(re[i-1] + nums[i], nums[i]);
            if (result < re[i]) {
                result = re[i];
            }
            i++;
        }
        return result;
    }

    public int maxSubArray(int[] nums) {
        int pre = 0;
        int result = nums[0];
        for (int num : nums) {
            pre = Math.max(pre + num, num);
            result = Math.max(result, pre);
        }
        return result;
    }
    
    @Test
    public void testMaxSubArray () {
        int[] nums = {-2,1,-3,4,-1,2,1,-5,4};
        System.out.println(maxSubArray(nums));
    }
}
